const { resolve } = require('path');
const { curl, readdir, copyFile, deleteFile, exists, mkdir, stat, getFileSepChar, moveFile, writeFile, cal_media_length, call_ffmpeg, sleep } = require('./util');
const fileSepChar = getFileSepChar(__dirname);
const WORK_PATH_EV = resolve(__dirname, 'EV') + fileSepChar; // ev待转码文件夹，仅存放mp4
const WORK_PATH_SOURCE = resolve(__dirname, 'SOURCE') + fileSepChar; // 源资料文件夹
const WORK_PATH_EVOUT = resolve(__dirname, 'EV_OUT') + fileSepChar; // EV转码完成文件，待分发到成员目录
const WORK_PATH_DEST = resolve(__dirname, 'DEST') + fileSepChar; // 最终转化根目录，下面按成员昵称文件夹分开
const SPLIT_CHAR = '@'
const VIDEO_FILE_TYPES = ['.mp4', '.ts'];
const TEMP_TYPES = [];

(async function () {
    await mkdir(WORK_PATH_EV);
    await mkdir(WORK_PATH_SOURCE);
    await mkdir(WORK_PATH_EVOUT);
    await mkdir(WORK_PATH_DEST);

    // 转码前调用
    await moveVideoFileFlat(WORK_PATH_SOURCE, WORK_PATH_SOURCE, WORK_PATH_EV, WORK_PATH_EVOUT)
    console.log(TEMP_TYPES);

    // // 转码后调用
    await afterEVWork(WORK_PATH_EVOUT, resolve(WORK_PATH_DEST, 'libin'))
    await afterEVWork(WORK_PATH_EV, WORK_PATH_SOURCE)
})();

function isVideo(filename) {
    if (!filename) return false;
    const fileExt = filename.substr(filename.lastIndexOf('.'));
    return VIDEO_FILE_TYPES.find(o => o === fileExt.toLowerCase()) != null;
}

/**
 * 转码前执行：移动文件（递归遍历）到目标文件价（扁平移动）
 * @param 源路径
 * @param 同源路径，后续递归子目录用
 * @param EV待转码路径
 * @param EV转出路径
 * @returns {Promise<void>}
 */
async function moveVideoFileFlat(rootDir, dir, destVideoDir, destOtherDir) {
    const filenames = await readdir(dir);
    for(let i=0; i<filenames.length; i++){
        const file = resolve(dir, filenames[i]);
        const _stat = await stat(file);
        if (!_stat.isFile()) {
            await moveVideoFileFlat(rootDir, file, destVideoDir, destOtherDir);
        } else {
            // 替换源文件的@为_
            let destFileName = resolve(dir, filenames[i].replace(eval(`/${SPLIT_CHAR}/g`), '_'));
            destFileName = destFileName.replace(rootDir, '').replace(fileSepChar==='/'?/\//g : /\\/g, SPLIT_CHAR);
            if (filenames[i].lastIndexOf('.')>0) {
                const _ext = filenames[i].substr(filenames[i].lastIndexOf('.'));
                if(TEMP_TYPES.indexOf(_ext) < 0)
                    TEMP_TYPES.push(_ext)
            }
            if (isVideo(destFileName)) {
                await moveFile(file, resolve(destVideoDir, destFileName));
                // console.log(file, resolve(destVideoDir, destFileName))
            } else {
                await copyFile(file, resolve(destOtherDir, destFileName));
                // console.log(file, resolve(destOtherDir, destFileName))
            }
        }
    }
}

async function afterEVWork (evFinishWorkPath, personPath) {
    const filenames = await readdir(evFinishWorkPath);
    for(let i=0; i<filenames.length; i++){
        const file = resolve(evFinishWorkPath, filenames[i]);
        const destFile = resolve(personPath, filenames[i].replace(eval(`/${SPLIT_CHAR}/g`), fileSepChar).replace('_ev.mp4', '.mp4'));
        await moveFile(file, destFile)
    }
    // console.log(filenames)

}
